package org.whuims.web.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;
import org.whuims.entity.News;
import org.whuims.service.news.NewsService;

import javax.servlet.ServletRequest;
import java.util.Map;

/**
 * Created by Roger on 2016/12/28.
 */
@Controller
@RequestMapping("/admin/news")
public class NewsAdminController {

    private static final String PAGE_SIZE = "10";

    @Autowired
    private NewsService newsService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                       @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
                       Model model,
                       ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<News> newsPage = newsService.getNewsList(searchParams, pageNumber, pageSize, null);
        model.addAttribute("newsPage", newsPage);
        model.addAttribute("sortType", "auto");
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "admin/news/list";
    }


    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        newsService.deleteNews(id);
        redirectAttributes.addFlashAttribute("message", "删除条目成功");
        return "redirect:/admin/news/list";
    }

}
